/*
 +----------------------------------------------------------------------
 + Title        : 用户 pinia 存储
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2023-07-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 用户 pinia 存储
 +----------------------------------------------------------------------
*/

import { reqLoginAPI, reqMobileLoginAPI, reqWxMobileLoginAPI, reqRegisterAPI, reqEditUserAPI, reqEditMobileAPI, reqEditEmailAPI, reqChangePasswordAPI, reqRefreshTokenAPI } from "@/apis/user";
import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useUserStore = defineStore('user', () => {
    
    // 定义用户信息
    const profile = ref()

    // 定义收货地址信息
    const deliveryAddr = ref({})

    // 定义搜索历史
    const searchHistoryList = ref([])

    // 设置用户信息
    const setProfile = (data) => {
        profile.value = data
    }

    // 清除用户信息
    const clearProfile = () => {
        profile.value = undefined
    }

    // 设置收货地址信息
    const setDeliveryAddr = (data) => {
        deliveryAddr.value = data
    }

    // 清除收货地址信息
    const clearDeliveryAddr = () => {
        deliveryAddr.value = undefined
    }

    // 添加搜索历史
    const addSearchHistory = (value) => {
        // 当搜索历史个数大于9则需要删除最旧的历史
        if (searchHistoryList.value.length >= 9) {
            searchHistoryList.value.shift()
        }
        
        if(searchHistoryList.value.indexOf(value) == -1) {
            searchHistoryList.value.push(value)
        }
    }

    // 删除搜索历史
    const deleteSearchHistory = (value) => {
        let index = searchHistoryList.value.indexOf(value)
        if(index != -1) {
            searchHistoryList.value.splice(index, 1)
        }
    }

    // 清空搜索历史
    const clearSearchHistory = () => {
        if (searchHistoryList.value.length == 0) {
            return false
        }

        searchHistoryList.value = []
    }

    /**
     * 登录
     * @param data 
     * @param mode 
     */
    const login = async (data, mode = 1) => {
        let response = null
        if (mode == 1) { // 密码登录
            response = await reqLoginAPI(data)
        } else if (mode == 2) { // 手机号登录
            response = await reqMobileLoginAPI(data)
        } else if (mode == 3) { // 使用微信绑定的手机号登录
            response = await reqWxMobileLoginAPI(data)
        }
        
        const result = response.data
        profile.value = result
    }

    /**
     * 注册
     * @param data 
     * @returns 
     */
    const register = async (data) => {
        const result = await reqRegisterAPI(data)
        return result.message
    }
		
    /**
     * 修改头像
     * @param data {avatar_url: "xxxxxxx"}
     * @returns 
     */
    const modifyAvatar = async (data) => {
        const result = await reqEditUserAPI(data)
        // 重新设置头像到 pinia
        profile.value.user.avatar_url = data.avatar_url
        return result.message
    }
		
    /**
     * 修改昵称
     * @param data {nick: "xxxxxxx"}
     * @returns 
     */
    const modifyNick = async (data) => {
        const result = await reqEditUserAPI(data)
        profile.value.user.nick = data.nick
        return result.message
    }
		
    /**
     * 修改手机号
     * @param data {mobile:123123123}
     * @returns 
     */
    const modifyMobile = async (data) => {
        const result = await reqEditMobileAPI(data.mobile)
        profile.value.user.mobile = data.mobile
        return result.message
    }
		
    /**
     * 修改邮箱
     * @param data {email:123123123@qq.com}
     * @returns 
     */
    const modifyEmail = async (data) => {
        const result = await reqEditEmailAPI(data.email)
        profile.value.user.email = data.email
        return result.message
    }

    /**
     * 编辑用户其他信息
     * @param data {gender: 1}
     * @returns 
     */
    const editOtherInfo = async (data) => {
        const result = await reqEditUserAPI(data)

        for (const key in data) {
            profile.value.user[key] = data[key]
        }
        return result.message
    }
		
    /**
     * 修改密码
     * @param data 
     * @returns 
     */
    const changePassword = async (data) => {
        const result = await reqChangePasswordAPI(data)
        return result.message
    }

    /**
     * 刷新token
     * @param fromUrl 
     * @returns 
     */
    const refreshToken = async (fromUrl) => {
        const unrefreshTokenUrls = [
            '/passwordLogin',
            '/messageLogin',
        ]
          
        // 如果存在token且是刷新token的url，则刷新token
        if (profile.value?.token && !unrefreshTokenUrls.includes(fromUrl)) {
            // 获取当前时间戳单位：毫秒数 1693538936799
            const currentTime = new Date().getTime()
            // token 过期时间
            const tokenExpireTime = (profile.value?.token_expire_time * 1000) - (900*1000)
            // console.log('tokenExpireTime =', tokenExpireTime);
            // const tokenExpireTime = 1693565529000 // 测试使用
                        
            // token已过期则刷新token
            if (currentTime >= tokenExpireTime && profile.value?.refresh_token != "") {
                const result = await reqRefreshTokenAPI(profile.value.refresh_token)
                // 设置刷新 token
                profile.value.refresh_token = result.data.refresh_token
                // 设置 token 过期时间
                profile.value.token_expire_time = result.data.token_expire_time
                // 设置新 token
                profile.value.token = result.data.token
                return result.message
            }
        }
    }

    // ------------------------- 计算属性 -------------------------
    // 有效搜索历史列表
    const validSearchHistoryList = computed(() => {
        return [...searchHistoryList.value].reverse()
    })

    return {
        profile,
        deliveryAddr,
        searchHistoryList,
        
        setProfile,
        clearProfile,
        login,
        register,
        modifyAvatar,
        modifyNick,
        modifyMobile,
        modifyEmail,
        changePassword,
        setDeliveryAddr,
        clearDeliveryAddr,
        refreshToken,
        editOtherInfo,
        addSearchHistory,
        deleteSearchHistory,
        clearSearchHistory,

        validSearchHistoryList
    }
},

// 持久化
{
    persist: true,
})